package com.letao.server.controller;

import com.letao.server.dto.AdminCommentDTO;
import com.letao.server.dto.Result;
import com.letao.server.dto.StockDTO;
import com.letao.server.dto.SuggectionQueryDTO;
import com.letao.server.entity.*;
import com.letao.server.service.*;
import com.letao.server.utils.UserHolderUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 商品管理模块控制类
 */
@RestController
@RequestMapping("/product")
@Slf4j
public class ProductController {
    @Resource
    ISpuService spuInfoService;
    @Resource
    IBaseCategoryService baseCategoryService;
    @Resource
    ISkuService skuInfoService;

    @Resource
    ISkuCommentService skuCommentService;


    @Resource
    IOrderService orderService;

    @Resource
    IOrderDetailService orderDetailService;


    /**
     * 增加SPU
     * 接口等级:管理员
     *
     * @param info spu信息
     * @return 返回的结果
     */
    @PostMapping("/spu")
    private Result insertSpu(@RequestBody SpuInfo info) {
        if (info.getDescript() == null || info.getSpuName() == null
                || info.getOneCategoryId() == null || info.getTwoCategoryId() == null) {
            return Result.fail("信息不完整");
        }
        BaseCategory one = baseCategoryService.getById(info.getOneCategoryId());
        BaseCategory two = baseCategoryService.getById(info.getTwoCategoryId());
        if (one == null || two == null) {
            return Result.fail("依赖错误");
        }
        if (info.getKeyWords() == null) {
            info.setKeyWords("无关键词");
        }
        info.setCreateTime(null);
        info.setId(null);
        info.setModifiedTime(null);
        info.setPriceHigh(null);
        info.setPriceLow(null);
        spuInfoService.save(info);
        log.info("管理员增加了Id={}的SPU", info.getId());
        return Result.success();
    }

    /**
     * 修改SPU信息
     * 接口等级:管理员
     *
     * @param info spu信息
     * @return 返回的结果
     */
    @PutMapping("/spu")
    private Result updateSpu(@RequestBody SpuInfo info) {
        if (info.getId() == null) {
            return Result.fail("未指定对象");
        }
        info.setModifiedTime(null);
        info.setCreateTime(null);
        info.setBit(null);
        spuInfoService.updateById(info);
        log.info("管理员修改了Id={}的SPU", info.getId());
        return Result.success();
    }

    /**
     * 删除SPU信息
     * 接口等级:管理员
     *
     * @param id SPU的Id
     * @return 返回的结果
     */
    @DeleteMapping("/spu/{id}")
    private Result deleteSpu(@PathVariable("id") Integer id) {
        SpuInfo spu = spuInfoService.getById(id);
        if (spu == null) {
            return Result.fail("依赖不存在");
        }
        if (spu.getBit() == 0) {
            return Result.fail("重复删除");
        }
        spu.setBit(0);
        List<SkuInfo> list = skuInfoService.query().eq("spu_id", id).eq("bit", 1).list();
        for (SkuInfo skuInfo : list) {
            skuInfo.setBit(0);
            skuInfoService.updateById(skuInfo);
        }
        spuInfoService.updateById(spu);
        return Result.success();
    }

    /**
     * 查询SPU信息
     * 接口等级:访客
     *
     * @param spuName       spu名称
     * @param oneCategoryId 一级分类
     * @param twoCategoryId 二级分类
     * @param keyWords      关键字
     * @param page          页码
     * @param pageSize      页大小
     * @return 返回的结果
     */
    @GetMapping("/spu")
    private Result querySpu(@RequestParam(required = false) Long id,
                            @RequestParam(required = false) String spuName,
                            @RequestParam(required = false) Integer oneCategoryId,
                            @RequestParam(required = false) Integer twoCategoryId,
                            @RequestParam(required = false) String keyWords,
                            @RequestParam(required = false) Integer hasStock,
                            @RequestParam(required = false, defaultValue = "1") Integer page,
                            @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        return spuInfoService.getPageInfo(id, spuName, oneCategoryId, twoCategoryId, keyWords, hasStock, page, pageSize);
    }

    @GetMapping("/spu/{id}")
    private Result querySpuS(@PathVariable Long id) {
        return Result.success(spuInfoService.getById(id));
    }

    /**
     * 获取推荐商铺信息
     * 接口等级:访客
     *
     * @return 返回的结果
     */
    @PostMapping("/spu/suggest")
    private Result suggestSpu(@RequestBody SuggectionQueryDTO dto) {
        if (dto.getPage() == null) dto.setPage(1);
        if (dto.getPageSize() == null) dto.setPageSize(10);
        return spuInfoService.suggest(dto.getQuery(), dto.getPage(), dto.getPageSize());
    }

    /**
     * 补全SPU信息
     * 接口等级:访客
     *
     * @param query 待补全字符串
     * @return 返回的结果
     */
    @GetMapping("/spu/complete")
    private Result completeSpu(@RequestParam String query) {
        return spuInfoService.complete(query);
    }

    /**
     * 增加SKU信息
     * 接口等级:管理员
     *
     * @param info SKU信息
     * @return 返回的结果
     */
    @PostMapping("/sku")
    private Result insertSku(@RequestBody SkuInfo info) {
        if (info.getDescript() == null ||
                info.getPrice() == null ||
                info.getSkuName() == null ||
                info.getSpuId() == null) {
            return Result.fail("信息不完整");
        }
        SpuInfo spu = spuInfoService.getById(info.getSpuId());
        if (spu == null) {
            return Result.fail("SPU不存在");
        }
        info.setId(null);
        info.setCreateTime(null);
        info.setModifiedTime(null);
        info.setHasImage(null);
        skuInfoService.save(info);
        if (info.getPrice() > spu.getPriceHigh()) spu.setPriceHigh(info.getPrice());
        if (info.getPrice() < spu.getPriceLow()) spu.setPriceLow(info.getPrice());
        spuInfoService.updateById(spu);
        return Result.success();
    }

    /**
     * 修改sku信息
     * 接口等级:管理员
     *
     * @param info sku信息
     * @return 返回的结果
     */
    @PutMapping("/sku")
    private Result updateSku(@RequestBody SkuInfo info) {
        if (info.getId() == null) {
            return Result.fail("信息不完整");
        }
        SkuInfo sku = skuInfoService.getById(info.getId());
        if (sku == null) {
            return Result.fail("对象不存在");
        }
        info.setHasImage(null);
        info.setCreateTime(null);
        info.setModifiedTime(null);
        info.setSpuId(null);
        info.setBit(null);
        skuInfoService.updateById(info);
        return Result.success();
    }

    /**
     * 删除sku信息
     * 接口等级:管理员
     *
     * @param id sku的Id
     * @return 返回的结果
     */
    @DeleteMapping("/sku/{id}")
    private Result deleteSku(@PathVariable("id") Long id) {
        SkuInfo sku = skuInfoService.getById(id);
        if (sku == null) {
            return Result.fail("对象不存在");
        }
        if (sku.getBit() == 0) {
            return Result.fail("重复删除");
        }
        SpuInfo spu = spuInfoService.getById(sku.getSpuId());
        sku.setBit(0);
        skuInfoService.updateById(sku);
        List<SkuInfo> list = skuInfoService.query()
                .eq("spu_id", spu.getId())
                .eq("bit", 1)
                .orderByAsc("price").list();
        if (list.isEmpty()) {
            spu.setPriceHigh((double) 0);
            spu.setPriceHigh((double) 10000000);
        } else {
            spu.setPriceHigh(list.get(list.size() - 1).getPrice());
            spu.setPriceLow(list.get(0).getPrice());
        }
        spuInfoService.updateById(spu);
        log.info("管理员删除了Id={}的SKU", id);
        return Result.success();
    }

    /**
     * 查询sku信息
     * 接口等级:访客
     *
     * @param spuId 所属spuId
     * @return 返回的结果
     */
    @GetMapping("/sku")
    private Result querySku(@RequestParam Long spuId) {
        return skuInfoService.getInfoList(spuId);
    }

    @GetMapping("/sku/{id}")
    private Result querySkuS(@PathVariable Long id) {
        return skuInfoService.getInfo(id);
    }

    /**
     * 用户增加评论
     * 接口等级: 用户
     *
     * @param info 评论信息
     * @return 返回的结果
     */
    @PostMapping("/comment")
    private Result addComment(@RequestBody SkuCommentInfo info) {
        if (info.getCommentTxt() == null ||  info.getSkuId() == null
                || info.getOrderId() == null || info.getAppraise() == null
                || info.getAppraise() < 1 || info.getAppraise() > 5) {
            return Result.fail("数据错误");
        }
        SpuInfo spu = spuInfoService.getById(info.getSpuId());
        SkuInfo sku = skuInfoService.getById(info.getSkuId());
        info.setSpuId(sku.getSpuId());
        OrderInfo order = orderService.getById(info.getOrderId());
        if (order == null) {
            return Result.fail("依赖不存在");
        }
        if (spu == null || sku == null) {
            return Result.fail("依赖不存在");
        }
        List<OrderDetail> list = orderDetailService.query().eq("order_id", info.getOrderId()).list();
        boolean flag = true;
        for (OrderDetail d : list) {
            if (Objects.equals(d.getSpuId(), info.getSpuId()) && Objects.equals(d.getSkuId(), info.getSkuId())) {
                flag = false;
                break;
            }
        }
        if (flag) {
            return Result.fail("依赖错误");
        }
        SkuCommentInfo one = skuCommentService.query().eq("spu_id", info.getSpuId())
                .eq("sku_id", info.getSkuId())
                .eq("order_id", info.getOrderId()).one();
        if (one != null) {
            return Result.fail("已评论");
        }
        info.setId(null);
        info.setUserId(UserHolderUtils.getUser().getId());
        info.setCreateTime(null);
        info.setCommentState(1);
        skuCommentService.save(info);
        OrderInfo orderInfo = orderService.getById(info.getOrderId());
        orderInfo.setCommentState(1);
        orderService.updateById(orderInfo);
        return Result.success();
    }

    /**
     * 管理员回复评论
     * 接口等级：管理员
     *
     * @return
     */
    @PutMapping("/comment/admin")
    private Result adminAddComment(
            @RequestBody AdminCommentDTO adminCommentDTO) {
        if (adminCommentDTO.getAdminComment() == null) {
            return Result.fail("需输入管理员评论");
        }
        ;
        SkuCommentInfo skuCommentInfo = skuCommentService.getById(adminCommentDTO.getCommentId());
        skuCommentInfo.setAdminComment(adminCommentDTO.getAdminComment());
        skuCommentInfo.setCommentState(2);
        skuCommentService.updateById(skuCommentInfo);
        OrderInfo orderInfo = orderService.getById(skuCommentService.getById(adminCommentDTO.getCommentId()).getOrderId());
        List<SkuCommentInfo> orderIdList = skuCommentService.query().eq("order_id", orderInfo.getId()).list();
        Boolean flag = true;
        for (SkuCommentInfo commentInfo : orderIdList) {
            if (commentInfo.getCommentState() == 1) {
                flag = false;
                break;
            }
        }
        if (flag)
            orderInfo.setCommentState(2);
        else
            orderInfo.setCommentState(1);
        orderService.updateById(orderInfo);
        return Result.success();
    }

    /**
     * 获取某商品的评论
     * 接口等级: 用户级
     *
     * @param spuId    商品的Id
     * @param page     页码
     * @param pageSize 页大小
     * @return 返回的结果
     */
    @GetMapping("/comment")
    private Result getComment(@RequestParam Long spuId,
                              @RequestParam(required = false, defaultValue = "1") Long page,
                              @RequestParam(required = false, defaultValue = "10") Long pageSize) {
        return skuCommentService.getComment(spuId, page, pageSize);
    }

    /**
     * 获取某sku的评论情况
     *
     * @param id
     * @return
     */

    @GetMapping("/comment/{id}")
    private Result getSkuComment(@PathVariable Long id) {
        return skuCommentService.getCommentSku(id);
    }

    /**
     * 获取订单下的评论
     *
     * @param orderId 订单id
     * @return
     */
    @GetMapping("/comment/order/{orderId}")
    private Result getOrderComment(@PathVariable Long orderId,@RequestParam(required = false) Long skuId) {
        return skuCommentService.getOrderComment(orderId,skuId);
    }


    /**
     * 增加库存
     * 接口等级: 管理员
     *
     * @param stock 库存信息
     * @return 返回的结果
     */
    @PostMapping("/stock")
    private Result addStock(@RequestBody StockDTO stock) {
        SkuInfo sku = skuInfoService.getById(stock.getSkuId());
        sku.setStock(sku.getStock() + stock.getStock());
        skuInfoService.updateById(sku);
        return Result.success();
    }


    @GetMapping("/new")
    private Result newFourSpu() {
        List<SpuInfo> list = spuInfoService.query().eq("bit", 1).orderByDesc("create_time").list();
        List<SpuInfo> returnList = new ArrayList<>();
        int size = Math.min(list.size(), 4);
        for (int i = 0; i < size; i++) {
            returnList.add(list.get(i));
        }
        return Result.success(returnList);
    }

    @GetMapping("/hot")
    private Result hotSpu() {
        return spuInfoService.hotSpu();
    }

}
